package com.yc.store.servlet;

import com.google.gson.Gson;
import com.yc.store.bean.Result;
import com.yc.store.bean.User;
import com.yc.store.biz.BizExeption;
import com.yc.store.biz.LoginBiz;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        WebApplicationContext ioc=
                WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
        LoginBiz loginBiz = ioc.getBean(LoginBiz.class);

        User user = new User();
        user.setName(req.getParameter("name"));
        user.setPwd(req.getParameter("pwd"));

        System.out.println("user：" + user.toString());

        Result result;
        try {
            User user1 = loginBiz.login(user);

            if(user1 == null){
                result = new Result(500,"账户或密码错误，请重新输入",user);
            }else{
                result = new Result(200,"登录成功",user);
                //将登录成功获取的用户信息保存到cookie中
                req.getSession().setAttribute("user",user1);
            }
        } catch (BizExeption e) {
            result = new Result(501,e.getMessage(),user);
        }

        resp.setContentType("application/json;charset=utf-8");
        Gson gson = new Gson();
        String json = gson.toJson(result);
        resp.getWriter().append(json);
    }
}
